package com.etc.testnio.testio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.CountDownLatch;

/**
 * @author: knowno
 * @create: 2024-09-12 14:16
 * @Version 1.0
 **/
public class FileCopy {

    public static void main(String[] args) {
        copyFile("G:\\01-诚毅软工21-后端1班\\2-授课期\\1-标准化教案\\第1周Java面向对象和常见API.rar", "G:\\01-诚毅软工21-后端1班\\1.rar");
    }

    /**
     * @param src  原文件的位置[完整路径]G:\01-诚毅软工21-后端1班\2-授课期\1-标准化教案\第1周Java面向对象和常见API.rar
     * @param dest 目标位置[完整路径] G:\01-诚毅软工21-后端1班\第1周Java面向对象和常见API.rar
     */
    public static void copyFile(String src, String dest) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            //创建输入流
            fileInputStream = new FileInputStream(src);
            //创建输出流
            fileOutputStream = new FileOutputStream(dest);

            //通过fileInputStream /fileOutputStream 获取FileChannel对象
            FileChannel inChannel = fileInputStream.getChannel();
            FileChannel outChannel = fileOutputStream.getChannel();

//            //使用transferTo复制文件
//            public abstract long transferTo(long position, long count,
//            WritableByteChannel target)
//            System.out.println(inChannel.size());
//            //  int var8 = (int)Math.min(var3, 2147483647L);
//            inChannel.transferTo(0, inChannel.size(), outChannel);
            long size = inChannel.size();
            long position = 0;
            while (size > 0) {
                long c = inChannel.transferTo(position, inChannel.size(), outChannel);
                position += c;
                size -= c;
            }


            inChannel.close();
            outChannel.close();
            System.out.println("复制成功!");


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            //释放资源
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }
}
